/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * CertificateDialog.java
 *
 * Created on Jan 27, 2012, 11:09:19 PM
 */
package it.j4ops.gui.dialog;

import it.j4ops.sign.provider.KeyIDAndX509Cert;
import it.j4ops.util.DNParser;
import it.j4ops.util.X509Util;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author zanutto
 */
public class CertificateDialog extends javax.swing.JDialog {
    private CertificateTableModel certificateTableModel = new CertificateTableModel();
    private List<KeyIDAndX509Cert> lstKeyAndX509Cert;
    private KeyIDAndX509Cert x509CertSelected;
    
    /** Creates new form CertificateDialog */
    public CertificateDialog(java.awt.Frame parent, boolean modal, final List<KeyIDAndX509Cert> lstKeyAndX509Cert) {
        super(parent, modal);
        this.lstKeyAndX509Cert = lstKeyAndX509Cert;       
        initComponents();
        certificateTableModel.removeAll();
        for (KeyIDAndX509Cert cert : lstKeyAndX509Cert) {
            certificateTableModel.addKeyIDAndX509Cert(cert);
        }
    }
    
    public KeyIDAndX509Cert getX509CertSelected () {
        return x509CertSelected;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jbutOk = new javax.swing.JButton();
        jbutCancel = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtabCertificates = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Select Certificate");

        jbutOk.setText("OK");
        jbutOk.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbutOkActionPerformed(evt);
            }
        });

        jbutCancel.setText("Cancel");
        jbutCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbutCancelActionPerformed(evt);
            }
        });

        jtabCertificates.setModel(certificateTableModel);
        jScrollPane1.setViewportView(jtabCertificates);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 674, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jbutOk, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jbutCancel)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 177, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jbutOk)
                    .addComponent(jbutCancel))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jbutOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbutOkActionPerformed
        if (jtabCertificates.getSelectedRow() >= 0) {
            x509CertSelected = lstKeyAndX509Cert.get(jtabCertificates.getSelectedRow());
            dispose();   
        }
    }//GEN-LAST:event_jbutOkActionPerformed

    private void jbutCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbutCancelActionPerformed
        x509CertSelected = null;
        dispose(); 
    }//GEN-LAST:event_jbutCancelActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(CertificateDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(CertificateDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(CertificateDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(CertificateDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                List<KeyIDAndX509Cert> lstKeyAndX509Cert = new ArrayList<KeyIDAndX509Cert>();
                CertificateDialog dialog = new CertificateDialog(new javax.swing.JFrame(), true, lstKeyAndX509Cert);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton jbutCancel;
    private javax.swing.JButton jbutOk;
    private javax.swing.JTable jtabCertificates;
    // End of variables declaration//GEN-END:variables
}

class CertificateTableModel extends DefaultTableModel {   
    
    public CertificateTableModel () {
        setDataVector(new Object[0][0], new String[]{"Label", "Owner", "SerialNumber", "Organization", "Issuer", "KeyUsage", "NotBefore", "NotAfter"});
    }  
    
    public void removeAll () {
        for (int index = 0; index < getRowCount(); index++) {
            removeRow(index);      
        }
        getDataVector().clear();        
    }
    
    public void addKeyIDAndX509Cert (KeyIDAndX509Cert cert) {
        SimpleDateFormat sdf = new SimpleDateFormat ("dd-MM-yyyy HH:mm:ss");
        insertRow(getRowCount(), new String[]{cert.getCertLabel(),
                                              DNParser.parse(cert.getX509Cert().getSubjectDN().toString(), "CN"),
                                              DNParser.parse(cert.getX509Cert().getSubjectDN().toString(), "SERIALNUMBER"),
                                              DNParser.parse(cert.getX509Cert().getSubjectDN().toString(), "O"),
                                              DNParser.parse(cert.getX509Cert().getIssuerDN().toString(), "CN"),
                                              X509Util.getDescrKeyUsage(cert.getX509Cert()),
                                              sdf.format(cert.getX509Cert().getNotBefore()),
                                              sdf.format(cert.getX509Cert().getNotAfter())});           
    }    
    
    @Override
    public boolean isCellEditable(int row, int column) {
       return false;
    }    
                         
}